package com.shanyu.nicefish.config;

import com.alibaba.fastjson.JSON;
import com.shanyu.nicefish.common.JsonResult;
import com.shanyu.nicefish.common.JwtTokenUtils;
import com.shanyu.nicefish.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 *
 * @blame czj Team
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private HrService hrService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        System.out.println("登陆成功！");
        response.setContentType("application/json;charset=UTF-8");
        try {
            UserDetails details = hrService.loadUserByUsername(authentication.getName());

            String token = JwtTokenUtils.TOKEN_PREFIX  + JwtTokenUtils.createToken(details, false);

            // 重定向
            response.setHeader(JwtTokenUtils.TOKEN_HEADER, token);
            response.getWriter().write(JSON.toJSONString(JsonResult.success(token)));
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(JsonResult.fail(401, "创建token失败，请与管理员联系")));
        }

    }

}
